/*
 *  mini-SaaS
 *  Application for developing Software as a Service (SaaS) 
 *  Copyright (c) 2011 Anand Sudhakaran, Bryce Holton, Chao Zhang
 *  ASU
 *
 *  This file is part of mini-SaaS.
 *
 *  mini-SaaS is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  mini-SaaS is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
 *  along with mini-SaaS; if not, see <http://www.gnu.org/licenses/>. 
 *
 */
 package loginbean;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBManager {

	private static DBManager instance = null;

	private static String driverName = "com.mysql.jdbc.Driver";
	private static String jdbcProtocol = "jdbc:mysql:";
	private String hostName = "localhost";
	private String port = "3306";
	private static String connectionString = "mydb";
	private static Driver registeredDriver = null;
	private Connection connection = null;
	private String userName = "root";
	private String password = "admin";

	static {
	    registerDriver();
	}

    public static DBManager getInstance() {
        if (instance == null)
            instance = new DBManager();
        return instance;
    }

    private static void registerDriver() {
        if (registeredDriver != null)
            return;
        try {
            Class driver_cls = Class.forName(driverName);
            registeredDriver = (Driver) driver_cls.newInstance();
            DriverManager.registerDriver(registeredDriver);
        } catch (Exception e) {
            System.out.println("ERROR -  in registerDriver() of DBManager.");
        }
    }
//call new DBManager().getDatabaseConnection();
    public Connection getDatabaseConnection() throws Exception {
        try {
            if (connection == null || connection.isClosed()) {
                String con_url = jdbcProtocol + "//" + hostName + ":" + port + "/" + connectionString;
                connection = DriverManager.getConnection(con_url, userName, password);
            }
        } catch (SQLException e) {
            throw new Exception("ERROR - getDatabaseConnection() Method Failed - " + e.getMessage());
        }
        return connection;
    }
}
